package com.bignerdranch.android.furnitureapplication;

import android.content.SharedPreferences;
import android.media.Image;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bignerdranch.android.furnitureapplication.entity.FurnitureInfoBean;
import com.bignerdranch.android.furnitureapplication.entity.UserInfoBean;
import com.bignerdranch.android.furnitureapplication.net.LoginResponse;
import com.bignerdranch.android.furnitureapplication.net.RetrofitHelper;
import com.bumptech.glide.Glide;

import java.text.SimpleDateFormat;
import java.util.Date;

import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class BuyFurnitureActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView furnitureImage;
    private TextView priceText;
    private TextView furnitureTitle;
    private FurnitureInfoBean mFurnitureInfoBean;
    private TextView isLike;
    private ImageView collectionImage;
    private ImageView backImage;
    private TextView buyNow;
    private boolean collection;
    private String getUserAccount;
    private LoginResponse mLoginResponse;
    private UserInfoBean mUserInfoBean;
    private int getFurnitureId;
    private double getUserBalance;
    BottomSheetDialog sheetDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buy_furniture);
        mFurnitureInfoBean = (FurnitureInfoBean) getIntent().getSerializableExtra("furn_info");
        getFurnitureId = mFurnitureInfoBean.getId();

        SharedPreferences preferences = getSharedPreferences("user_info",MODE_PRIVATE);
        getUserAccount = preferences.getString("user_account", "bbchond");

        initViews();
        Glide.with(this).load(mFurnitureInfoBean.getRedwood_image()).into(furnitureImage);
        priceText.setText("￥" + mFurnitureInfoBean.getRedwood_price());
        furnitureTitle.setText(mFurnitureInfoBean.getRedwood_name());
    }

    private void initViews() {
        furnitureImage = findViewById(R.id.furniture_image);
        priceText = findViewById(R.id.furniture_price);
        furnitureTitle = findViewById(R.id.furniture_info_title);
        isLike = findViewById(R.id.is_collection);
        backImage = findViewById(R.id.back_button);
        collectionImage = findViewById(R.id.collection_image);
        collectionImage.setOnClickListener(this);
        buyNow = findViewById(R.id.buy_now);
        buyNow.setOnClickListener(this);
        backImage.setOnClickListener(this);
        isCollection(getUserAccount, getFurnitureId);
        getUserInfo(getUserAccount);
    }

    private void isCollection(String userAccount, int furnitureId) {
        RetrofitHelper.getNewsService()
                .isInCollection(userAccount, furnitureId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onCompleted() {
                        if (mLoginResponse.getStatus().equals("true")) {
                            collectionImage.setImageResource(R.mipmap.collection_true);
                            isLike.setText("已收藏");
                            collection = true;
                        } else {
                            collectionImage.setImageResource(R.mipmap.collection_false);
                            isLike.setText("收藏");
                            collection = false;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        mLoginResponse = loginResponse;
                    }
                });
    }

    private void addFurnitureCollection(String userAccount, int classId) {
        RetrofitHelper.getNewsService()
                .addFurnitureCollectionInfo(userAccount, classId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onCompleted() {
                        if (mLoginResponse.getStatus().equals("true")) {
                            Toast.makeText(BuyFurnitureActivity.this, "收藏成功！", Toast.LENGTH_SHORT).show();
                            collectionImage.setImageResource(R.mipmap.collection_true);
                            isLike.setText("已收藏");
                            collection = true;
                        } else {
                            Toast.makeText(BuyFurnitureActivity.this, "收藏失败，请稍后再试", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        Toast.makeText(BuyFurnitureActivity.this, "网络错误！", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        mLoginResponse = loginResponse;
                    }
                });
    }

    private void cancelFurnitureCollectionInfo(String userAccount, int classId) {
        RetrofitHelper.getNewsService()
                .cancelFurnitureCollectionInfo(userAccount, classId)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onCompleted() {
                        if (mLoginResponse.getStatus().equals("true")) {
                            Toast.makeText(BuyFurnitureActivity.this, "已取消收藏", Toast.LENGTH_SHORT).show();
                            collectionImage.setImageResource(R.mipmap.collection_false);
                            isLike.setText("收藏");
                            collection = false;
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        mLoginResponse = loginResponse;
                    }
                });
    }

    private void getUserInfo(String userAccount) {
        RetrofitHelper.getAccountService()
                .getUserInfo(userAccount)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserInfoBean>() {
                    @Override
                    public void onCompleted() {
                        getUserBalance = mUserInfoBean.getUser_balance();
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(UserInfoBean userInfoBean) {
                        mUserInfoBean = userInfoBean;
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.buy_now:
                showBottomDialog();
                break;
            case R.id.back_button:
                finish();
                break;
            case R.id.collection_image:
                if (collection) {
                    cancelFurnitureCollectionInfo(getUserAccount, getFurnitureId);
                } else {
                    addFurnitureCollection(getUserAccount, getFurnitureId);
                }
                break;
        }
    }

    private void showBottomDialog() {
        sheetDialog = new BottomSheetDialog(this);
        View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_bottomsheet, null);
        TextView furnitureName = dialogView.findViewById(R.id.furniture_name);
        TextView furniturePrice = dialogView.findViewById(R.id.furniture_price);
        TextView userBalance = dialogView.findViewById(R.id.user_balance);
        TextView payType = dialogView.findViewById(R.id.pay_type);
        Button submitButton = dialogView.findViewById(R.id.submit_button);
        furnitureName.setText(mFurnitureInfoBean.getRedwood_name());
        furniturePrice.setText(String.valueOf(mFurnitureInfoBean.getRedwood_price()));
        userBalance.setText("￥" + getUserBalance);
        payType.setText("用户钱包");
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (getUserBalance > mFurnitureInfoBean.getRedwood_price()) {
                    Toast.makeText(BuyFurnitureActivity.this, "支付中，请稍候...", Toast.LENGTH_SHORT).show();
                    userPay();
                } else {
                    Toast.makeText(BuyFurnitureActivity.this, "余额不足，请充值！", Toast.LENGTH_SHORT).show();
                }
            }
        });
        sheetDialog.setContentView(dialogView);
        sheetDialog.show();
    }

    private void userPay() {
        RetrofitHelper.getAccountService()
                .updateUserBalance(getUserAccount, getUserBalance - mFurnitureInfoBean.getRedwood_price())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onCompleted() {
                        if (mLoginResponse.getStatus().equals("true")) {
                            Toast.makeText(BuyFurnitureActivity.this, "支付成功！", Toast.LENGTH_SHORT).show();
                            addToOrder();
                            finish();
                            sheetDialog.dismiss();
                        } else {
                            Toast.makeText(BuyFurnitureActivity.this, "支付失败，请稍候再试", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        mLoginResponse = loginResponse;
                    }
                });
    }

    private void addToOrder() {
        RetrofitHelper.getNewsService()
                .addOrderInfo(getUserAccount, mFurnitureInfoBean.getId(), getNowTime(), mFurnitureInfoBean.getRedwood_price())
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginResponse loginResponse) {
                        mLoginResponse = loginResponse;
                    }
                });
    }

    public static String getNowTime(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }
}

